import React, { useRef, useState, useEffect } from 'react';
import './App.css';
import PetDisplay from './components/PetDisplay';
import StatusBar from './components/StatusBar';
import ActionButtons from './components/ActionButtons';
import GameInfo from './components/GameInfo';
import PetSelection from './components/PetSelection';
import TaskSystem from './components/TaskSystem';
import MapScreen from './components/MapScreen';
import Notification from './components/Notification';

import { usePetState } from './hooks/usePetState';
import { useGameInfo } from './hooks/useGameInfo';
import { useAvailablePets } from './hooks/useAvailablePets';
import { useGameActions } from './hooks/useGameActions';
import { useGameTimer } from './hooks/useGameTimer';
import { useGamePersistence } from './hooks/useGamePersistence';

const App = () => {
  const [gameStarted, setGameStarted] = useState(false);
  const [showMap, setShowMap] = useState(false);
  const [notification, setNotification] = useState({
    message: '',
    isVisible: false
  });

  const [petState, setPetState] = usePetState();
  const [gameInfo, setGameInfo] = useGameInfo();
  const [availablePets, setAvailablePets, generateAvailablePets] = useAvailablePets();
  
  const petRefs = useRef({});
  const taskSystemRef = useRef();

  const gameActions = useGameActions(petState, setPetState, gameInfo, setGameInfo, taskSystemRef);
  
  useGameTimer(gameStarted, setGameInfo, setPetState);

  const handleSelectPet = (petType) => {
    const petNames = {
      cat: '小咪',
      dog: '旺财',
      rabbit: '兔兔',
      hamster: '仓仓'
    };
    
    setPetState(prev => ({
      ...prev,
      name: petNames[petType] || '小萌',
      type: petType
    }));
    
    generateAvailablePets();
    setGameStarted(true);
  };

  const handleCollectPet = (petId) => {
    const collectedPet = availablePets.find(pet => pet.id === petId);
    
    if (collectedPet) {
      setGameInfo(prev => ({
        ...prev,
        coins: prev.coins + 50,
        collectedPets: [...prev.collectedPets, collectedPet]
      }));
      
      setAvailablePets(prev => prev.filter(pet => pet.id !== petId));
      
      setNotification({
        message: `恭喜！你收集了${collectedPet.name}！获得50金币奖励！`,
        isVisible: true
      });
    }
  };

  const handleCompleteTask = (reward) => {
    setGameInfo(prev => ({
      ...prev,
      coins: prev.coins + reward
    }));
    
    setNotification({
      message: `任务完成！获得 ${reward} 金币奖励！`,
      isVisible: true
    });
  };

  const handleEnterMap = () => setShowMap(true);

  const handleReturnFromMap = () => {
    setShowMap(false);
    if (availablePets.length === 0) {
      generateAvailablePets();
    }
  };

  const handleCloseNotification = () => {
    setNotification(prev => ({
      ...prev,
      isVisible: false
    }));
  };

  const { saveGame, loadGame } = useGamePersistence(
    petState,
    setPetState,
    gameInfo,
    setGameInfo,
    setGameStarted,
    availablePets,
    setAvailablePets,
    setNotification
  );

  // 添加自动保存功能
  useEffect(() => {
    if (gameStarted) {
      // 尝试每分钟自动保存
      const autoSaveInterval = setInterval(saveGame, 60000);
      return () => clearInterval(autoSaveInterval);
    }
  }, [gameStarted, saveGame]);

  // 添加自动加载功能
  useEffect(() => {
    if (!gameStarted) {
      loadGame();
    }
  }, [gameStarted, loadGame]); // 添加正确的依赖项

  // 修改 PetSelection 组件的渲染部分
  return (
    <div className="game-container">
      <div className="main-content">
        {!gameStarted ? (
          <>
            <PetSelection onSelectPet={handleSelectPet} />
            <button
              onClick={loadGame}
              style={{
                position: 'absolute',
                top: '20px',
                right: '20px',
                padding: '10px 20px',
                backgroundColor: '#4CAF50',
                color: 'white',
                border: 'none',
                borderRadius: '20px',
                cursor: 'pointer',
                boxShadow: '0 3px 5px rgba(0, 0, 0, 0.2)'
              }}
            >
              加载存档
            </button>
          </>
        ) : showMap ? (
          <MapScreen 
            availablePets={availablePets} 
            onCollectPet={handleCollectPet} 
            onReturn={handleReturnFromMap} 
          />
        ) : (
          <>
            <GameInfo gameInfo={gameInfo} petState={petState} />
            <PetDisplay petState={petState} />
            <StatusBar petState={petState} />
            <TaskSystem 
              ref={taskSystemRef}
              petState={petState} 
              gameInfo={gameInfo} 
              onCompleteTask={handleCompleteTask} 
            />
            <ActionButtons 
              handleFeed={gameActions.handleFeed}
              handlePlay={gameActions.handlePlay}
              handleClean={gameActions.handleClean}
              handleSleep={gameActions.handleSleep}
              petState={petState}
              gameInfo={gameInfo}
            />
            
            <button 
              className="enter-map-button" 
              onClick={handleEnterMap}
              style={{
                position: 'absolute',
                bottom: '20px',
                right: '20px',
                padding: '10px 20px',
                backgroundColor: '#4CAF50',
                color: 'white',
                border: 'none',
                borderRadius: '20px',
                cursor: 'pointer',
                boxShadow: '0 3px 5px rgba(0, 0, 0, 0.2)',
                zIndex: 100
              }}
            >
              进入地图收集宠物
            </button>
            
            {/* 添加保存按钮 */}
            <button
              onClick={saveGame}
              style={{
                position: 'absolute',
                top: '20px',
                right: '20px',
                padding: '10px 20px',
                backgroundColor: '#4CAF50',
                color: 'white',
                border: 'none',
                borderRadius: '20px',
                cursor: 'pointer',
                boxShadow: '0 3px 5px rgba(0, 0, 0, 0.2)',
                zIndex: 100
              }}
            >
              保存游戏
            </button>
            
            {/* ... 现有的地图按钮 ... */}
          </>
        )}
      </div>

      <Notification 
        message={notification.message}
        isVisible={notification.isVisible}
        onClose={handleCloseNotification}
      />
    </div>
  );
};

export default App;